<?php

// +----------------------------------------------------------------------
// | 前台页面公共控制器
// +----------------------------------------------------------------------

namespace Common\Controller;

define("HELLYEMS_VERSION", C("HELLYEMS_VERSION"));

class Base extends CommonSet {

    //初始化
    protected function _initialize() {
        parent::_initialize();

        //类别
       /* if(empty(cache('Categorys'))){
            $this->category=$this->getCate();
        }else{
            $this->category=cache('Categorys');
        }*/

    //    cache('Categorys',null);

        $curr=strtolower(CONTROLLER_NAME);
        $cs=strtolower(ACTION_NAME);
        if($curr == 'suipai' && $cs == 'splist'){
        }else{
            if($curr != 'index'){
                $this->start_auto();
            }
            
            $this->getUserInfo();
            $this->getbot();
            //类别数组
            $this->assign("cate", $this->getCate());
            //当前导航
            $this->assign('nav', $this->getNav());
            //二级菜单
            $this->assign('twoNaves',$this->twoNaves());
            //站内消息数
            $this->assign('sysmsgnum',$this->getsysmsgnum());
        }
        
    }


    //获取登录用户的信息
    final public function getUserInfo(){
        if(service('Passport')->userid){
            $this->userid = (int)service("Passport")->userid;
            $this->uname = service("Passport")->uname;
            $this->userinfo = service("Passport")->getInfo();
            $this->assign('userinfo',$this->userinfo);
        }
    }

    /**
     * 获取类别
     * @return mixed 类别或缓存
     */
    public function getCate(){
        $cate=M('Category')->field('cateid,catename,arrchildid,image')->where(array('child'=>1))->order("sort DESC")->select();
        foreach($cate as $key=>$value){
            $cate[$key]['childcate']=M('Category')->field('cateid,catename,image')->where(array('parentid'=>$value['cateid']))->order("sort DESC")->select();
        }
        cache('Categorys',$cate);
        return $cate;
    }

    /**
     * 获取广告
     * @param $menu 所属菜单
     * @param $position 位置
     * @param $from 从第几个开始
     * @param int $num 数量
     * @return mixed 返回数据/数组
     */
    public function getAdvert($menu,$position,$from,$num=1){
        $adModel=M('Advert');
        $where['status']=array('EQ',true);
        $where['menu']=array('EQ',$menu);
        $where['position']=array('EQ',$position);
        $field=array('image,linkurl,title');
        if($num<2){
            $ad=$adModel->where($where)->field($field)->order('sort DESC,id DESC')->limit($from,$num)->find();
        }else{
            $ad=$adModel->where($where)->field($field)->order('sort DESC,id DESC')->limit($from,$num)->select();
        }
        cache('advert',$ad);
        return $ad;
    }


    /**
     * 获取站内未读数目
     */
//     public function getsysmsgnum(){
//         $model=M('Sysmsg');
//         $num=$model->where('status=true and ifread=false and create_time>='.service("Passport")->getInfo()['create_time'].' and userid='.$this->userid.' or userid=""')->count();
//         return $num;
//     }
// 	public function getsysmsgnum()
// 	{
// 		$sys = M('Sysmsg');
// 		$ids = $sys->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
// 		if($ids)
// 		{
// 			$arr = array();
// 			foreach($ids as $k => $v)
// 			{
// 				$temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
// 				if(!isset($temp_type))
// 				{
// 					$info['sysid'] = $v['id'];
// 					$info['userid'] = $this->userid;
// 					$info['ifread'] = 0;
// 					M('SysmsgLog')->data($info)->add();
// 					$arr[] = $v;
// 				}
// 				if($temp_type == 0)
// 				{
// 					$arr[] = $v;
// 				}
// 			}
// 		}
// 		$num = count($arr);
// 		return $num;
// 	}

    public function getsysmsgnum()
    {
        $arr = array();
         
        $message1 = M('UserMessage')->where("ifread=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->count();
        $message2 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.ifread=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $message3 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.ifread=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $message4 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.ifread=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $arr['message'] = $message1 + $message2 + $message3 + $message4;
         
        $dig = M('Dig');
        $fav = M('UserFavorite');
        $dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
        $fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
        $arr['digfav'] = $dig_count + $fav_count;
         
        $arr['fans'] = M('UserFans')->where("ifread=0 and userid=%d and status=1", array($this->userid))->count();
         
        $suipai_count = M('Suipai')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        $works_count = M('Works')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        $arr['pro'] = $suipai_count + $works_count;
         
        $where = "A.ifreadto=0 and B.userid=".$this->userid;
        $arr['copypro'] = M('Works')->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
         
        $arr['score'] = M('UserDynamic')->where("status=1 and ifread=0 and userid=%d", array($this->userid))->count();
         
        $arr['listtry'] = M('TryApply')->where('status <> 0 and userid='.$this->userid." and ifread=0")->count();
         
        $yarr = array();
        $ids = M('Sysmsg')->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
        if($ids)
        {
            foreach($ids as $k => $v)
            {
                $temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
                if(!isset($temp_type))
                {
                    $info['sysid'] = $v['id'];
                    $info['userid'] = $this->userid;
                    $info['ifread'] = 0;
                    $info['is_del'] = 0;
                    M('SysmsgLog')->data($info)->add();
                    $yarr[] = $v;
                }
                if($temp_type == 0)
                {
                    $yarr[] = $v;
                }
            }
        }
        $arr['sysmsg'] = count($yarr);
         
        $num = $arr['message'] + $arr['digfav'] + $arr['fans'] + $arr['pro'] + $arr['copypro'] + $arr['score'] + $arr['listtry'] + $arr['sysmsg']; 
        return $num;
    }
    

    /**
     * 获取导航
     * @return array
     */
    public function getNav(){
        $nav=array(
            'index'=>array(
                'link'=>'index',
                'title'=>'首页',
            ),
            'dongtai'=>array(
                'link'=>'dongtai',
                'title'=>'烘焙食谱',
            ),
            'news'=>array(
                'link'=>'news',
                'title'=>'烘焙资讯',
            ),
           
            /*'jifen'=>array(
                'link'=>'jifen',
                'title'=>'名师教学',
            ),*/
             'suipai'=>array(
                'link'=>'suipai',
                'title'=>'随手拍',
            ),
            'jifen'=>array(
                'link'=>'jifen',
                'title'=>'活动',
            )
         );
        $curr=strtolower(CONTROLLER_NAME);
        $cs=strtolower(ACTION_NAME);
        if($curr =='try' ){
            $curr = 'jifen';
        }else if(($cs == 'category' && $curr =='index') || $curr=='works' || $curr == 'search'){
                $curr = 'dongtai';
            }

        foreach($nav as $key => $value){
            if($curr==$key){
                $nav[$key]['act']=' act';
            }
        }
        return $nav;
    }
    
    //二级菜单
    public function twoNaves(){
        $model = M('Category');
        $nav = $model->select();
        $twoNav = array();
        foreach ($nav as $key => $value) {
            if($value['parentid'] == 0){
                $twoNav[$value['cateid']] = $value;
            }else{
                $twoNav[$value['parentid']]['sod'][] = $value;
            }
        }
        return $twoNav;
    }

    /**
     * 获取试用导航
     * @return array
     */
    public function getTryNav(){
        $nav=array(
            'index'=>array(
                'link'=>'',
                'title'=>'试用首页',
            ),
            'newtry'=>array(
                'link'=>'newtry',
                'title'=>'最新试用',
            ),
            'lasttry'=>array(
                'link'=>'lasttry',
                'title'=>'往期试用',
            ),
            'report'=>array(
                'link'=>'report',
                'title'=>'试用报告',
            )
        );
        $curr=strtolower(ACTION_NAME);
        foreach($nav as $key => $value){
            if($curr==$key){
                $nav[$key]['act']=' act';
            }
        }
        return $nav;
    }

    /**
     * 获取试用导航
     * @return array
     */
    public function getUserNav(){
        $nav=array(
            'index'=>array(
                'link'=>'',
                'title'=>'个人信息',
            ),
            'sysmsg'=>array(
                //'link'=>'sysmsg',
                'link' => 'message',
                'title'=>'站内消息',
            ),
            'works'=>array(
                'link'=>'works',
                'title'=>'烘焙作品',
            ),
//             'suipai'=>array(
//                 'link'=>'suipai',
//                 'title'=>'随拍作品',
//             ),
//             'copy'=>array(
//                 'link'=>'copy',
//                 'title'=>'参考作品',
//             ),
            'jifen'=>array(
                'link'=>'jifen',
                'title'=>'积分换礼',
            ),
            'trylist'=>array(
                'link'=>'trylist',
                'title'=>'试用记录',
            ),
//             'report'=>array(
//                 'link'=>'report',
//                 'title'=>'试用报告',
//             ),
        	'repwd'=>array(
        		'link'=>'repwd',
        		'title'=>'修改密码',
            ),
           'teach'=>array(
               'link'=>'teach',
               'title'=>'导师申请',
           )
//             'message'=>array(
//                 'link'=>'message',
//                 'title'=>'留言管理',
//             )
        );

        $curr=strtolower(ACTION_NAME);
        foreach($nav as $key => $value){
            if($curr==$key){
                $nav[$key]['act']=' act';
            }
        }
        return $nav;
    }
    /**
     * 会员检测
     */
    public function check($type=0){
        if(!service('Passport')->userid){
            $backurl=trim($_SERVER['HTTP_REFERER']);
            $strdefault='只有会员才能进行此操作<a class="btn" href='.WEB_URL.'/user/login?backurl='.$backurl.'>登录</a>';
            $str='<form onsubmit="return false">';
            $str='<ul><li>用户名: <input type="text" class="input" name="uname" id="uname" /></li>';
            $str.='<li>密　码: <input type="password" class="input" name="password" id="password" /></li>';
            $str.='<li><input type="checkbox" name="autoLogin" id="autoLogin" value="1">两周内自动登录 <a href="#">忘记密码?</a></li>';
            $str.='<li><input type="submit" class="subbtn" id="loginSubmit" value="登录" /></li>';
            $str.='<li class="errmsg"></li>';
            $str.='<li style="margin-left: 45px">还没有注册烘焙圈? <a href="/user/login/register">马上注册</a></li>';
            $str.='<li><input type="hidden" id="backurl" value="'.$backurl.'"/></li>';
            $str.='</ul></form>';
            if($type==1){
                $this->error($str);
            }else{
                $this->error($strdefault);
            }
        }
    }

    //底部信息
    public function getbot(){
        $single=M('Single')->field('title,entitle')->where(array('status'=>true,'ifbot'=>true))->select();
        $this->assign('single',$single);
        $link=M('Link')->field('title,linkurl')->where(array('status'=>true,'iftj'=>true))->order('sort ASC')->limit(15)->select();
        $this->assign('link',$link);
    }
    
    public function start_auto()
    {
        
        $time = time();
        $list = M('Auto')->where("create_time < ".$time)->select();//print_r($list);
        if($list)
        {
            foreach($list as $k => $v)
            {
                if($v['type'] == 7)
                {
                    $stimes=strtotime(date('Y-m-d 00:00:00'))-6*24*3600;
                    $etimes=strtotime(date('Y-m-d 23:59:59'));
                    $wheres['userid']= array('EQ',$v['userid']);
					$wheres['credits'] = array('NEQ',10);
                    $wheres['action']= array('EQ','sign');
                    $wheres['create_time']=array(array('GT',$stimes),'and');
                    $signnum=getCount('UserDynamic',$wheres);
					
                    if($signnum ==6){
                        service('Passport')->userDynamic($v['userid'],10,'连续7天签到获取10个积分',1,'sign');
                    }
                    
                    $stime=strtotime(date('Y-m-d 00:00:00'));
                    $etime=strtotime(date('Y-m-d 23:59:59'));
                    $where['userid']= array('EQ',$v['userid']);
                    $where['action']= array('EQ','sign');
                    $where['create_time']=array(array('GT',$stime),array('LT',$etime),'and');
                    $mysign=getCount('UserDynamic',$where);
                    if($mysign>0){
                        $this->del_auto($v['id']);
                    }
                    else 
                    {
                        $result=service('Passport')->userDynamic($v['userid'],2,'签到获取2个积分',1,'sign');
                        $this->del_auto($v['id']);
                    }
                }
                else 
                {
                    if($v['comment'] == 1){
                        unset($map);
                        unset($where);
                        if($v['type']==1){
                            $table='Works';
                            $map['workid']=$v['infoid'];
                            $type = 1;
                        }elseif($v['type']==2){
                            $table='Suipai';
                            $map['id']=$v['infoid'];
                            $type = 4;
                        }elseif($v['type']==3){
                            $table='Works';
                            $map['workid']=$v['infoid'];
                            $type = 1;
                        }elseif($v['type']==4){
                            $table='News';
                            $map['id']=$v['infoid'];
                            $type = 5;
                        }elseif($v['type']==5){
                            $table='Activity';
                            $map['id']=$v['infoid'];
                            $type = 6;
                        }elseif($v['type']==6)
                        {
                            $table="Teachlist";
                            $map['teachid']=$v['infoid'];
                            $type = 7;
                        }
                        $post['userid'] = $v['userid'];
                        $post['infoid'] = $v['infoid'];
                        $post['content'] = $v['message'];
                        $post['create_time'] = $v['create_time'];
                        $post['type'] = $type;
                            //当天第一次留言
                        $stime=strtotime(date('Y-m-d 00:00:00'));
                        $etime=strtotime(date('Y-m-d 23:59:59'));
                        $where['userid']= array('EQ',$this->userid);
                        $where['create_time']=array(array('GT',$stime),array('LT',$etime),'and');
                        
                        $todayMsgnum=M('UserMessage')->where($where)->count();
                        $post['parent_id'] = isset($post['parent_id']) ? intval($post['parent_id']) : 0;
                        if(D('Home/Commons')->sendMessage2($post,$type)){
                            if($todayMsgnum<1){
                                $userarr['upoint'] = array('exp','upoint+2');
                                M('User')->where(array('userid'=>$v['userid']))->save($userarr);
                            }
                            optMsgnum($table,$map,'add');
                             //   $this->success('感谢您的留言,正在刷新页面!');
                        }
                    }
                   
                    if($v['dig'] == 1)
                    {
                        if($v['type'] == 1 || $v['type'] == 3)
                        {
                            $get['infoid'] = $v['infoid'];
                            $get['userid']=$v['userid'];
                            $get['digtype'] = 1;                                
                            $workuid=M('Works')->where(array('workid'=>$get['infoid']))->getField('userid');
                            if($workuid != $v['userid']){
                                D('Home/Commons')->adddig($get,1);
                            }
                        }
                    }

                    if($v['fans'] == 1)
                    {
                        unset($where);
                        $get['myid'] = $v['userid'];
                        if($v['type'] == 1 || $v['type'] == 3)
                        {
                            $table = "Works";
                            $where['workid'] = $v['infoid'];
                        }
                        elseif($v['type'] == 2)
                        {
                            $table = "Suipai";
                            $where['id'] = $v['infoid'];
                        }
                        elseif($v['type'] == 6)
                        {
                            $table = "Teachlist";
                            $where['teachid'] = $v['infoid'];
                        }
                        $get['userid'] = M($table)->where($where)->getField('userid');
                        if($get['userid'] != $v['userid']){
                            D('Home/Commons')->addfans($get);
                        }
                    }
                    
                    if($v['fav'] == 1)
                    {
                        unset($where);
                        if($v['type'] == 1)
                        {
                            $table = "Works";
                            $where['workid'] = $v['infoid'];
                        } 
                        elseif($v['type'] == 6)
                        {
                            $table = "Teachlist";
                            $where['teachid'] = $v['infoid'];
                        }
                        $get['userid']=$v['userid'];
                        $workuid=M($table)->where($where)->getField('userid');
                        if($workuid != $v['userid']){
                            if($v['type'] == 1)
                            {
                                $get['type'] = 1;
                                $get['infoid'] = $v['infoid'];
                                D('Home/Commons')->addfavorite($get,1);
                            }
                            if($v['type'] == 6)
                            {
                                $get['type'] = 7;
                                $get['infoid'] = $v['infoid'];
                                $get['create_time'] = time();
                                $get['status'] = 1;
                                $count = M('Teachfav')->where(array('userid' => $v['userid'], 'infoid' => $v['infoid']))->count();
                                if($count == 0)
                                {
                                    M('Teachfav')->add($get);
                                }
                            }
                        }
                    }
                    $this->del_auto($v['id']);
                }
            }
        }
    }   

    public function del_auto($id = '')
    {
        if(!empty($id))
        {
            M('Auto')->where(array('id' => $id))->delete();
        }
    }


}